package com.whut.entryservice.mq.comsumer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.whut.clcommon.config.RabbitMQConfig;
import com.whut.entryservice.domain.dto.CancelEntryDTO;
import com.whut.entryservice.domain.dto.EntryDTO;
import com.whut.entryservice.domain.po.Entry;
import com.whut.entryservice.service.IEntryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description: RabbitMQ消费者
 * @Author: Zonghe Wang
 * @Date: 2025/5/4 17:42
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RabbitEntryConsumer {

    private final IEntryService entryService;

    @RabbitListener(queues = RabbitMQConfig.ENTRY_QUEUE)
    public void handleEntryMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        log.info("接收到消息：{}", message);
        if (StrUtil.isEmpty(message)) {
            return;
        }
        try {
            EntryDTO entryDTO = JSONUtil.toBean(message, EntryDTO.class);
            if (BeanUtil.hasNullField(entryDTO)) {
                log.error("接收到消息：{}，数据不完整", message);
                return;
            }
            Entry entry = BeanUtil.copyProperties(entryDTO, Entry.class);
            boolean success = entryService.createEntry(entry);
            if (!success) {
                log.error("接收到消息：{}，处理失败", message);
                channel.basicNack(tag, false, false); // 拒绝且不重新入队
            }
            channel.basicAck(tag, false); // 确认消息
        } catch (Exception e) {
            log.error("接收报名消息：{}，处理失败", message);
            try {
                channel.basicNack(tag, false, false); // 拒绝且不重新入队
            } catch (IOException ex) {
                log.error("消息拒绝失败:{}", message);
            }
        }
    }

    @RabbitListener(queues = RabbitMQConfig.CANCEL_ENTRY_QUEUE)
    public void handleCancelEntryMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        log.info("接收到消息：{}", message);
        if (StrUtil.isEmpty(message)) {
            return;
        }
        try {
            CancelEntryDTO dto = JSONUtil.toBean(message, CancelEntryDTO.class);
            entryService.executeRedisOperations(dto);
        } catch (Exception e) {
            log.error("接收取消报名消息：{}，处理失败", message);
        }
    }

}
